import { _decorator, Collider2D, Component, Intersection2D, Label, Node, PolygonCollider2D, UITransform, v2, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TestPolygonPolygon')
export class TestPolygonPolygon extends Component {
    @property(PolygonCollider2D)
    polygonCollider1: PolygonCollider2D = null

    @property(PolygonCollider2D)
    polygonCollider2: PolygonCollider2D = null

    @property(Label)
    label: Label = null


    /**
     * 将PolygonCollider2D中points转换为世界坐标下
     * @param pcCom 
     * @returns 世界坐标下Points
     */
    private polygonColliderToWorldPoints(pcCom: PolygonCollider2D): Vec2[] {
        const worldPoints: Vec2[] = []
        const uitransform = pcCom.node.getComponent(UITransform)
        for (let index = 0; index < pcCom.points.length; index++) {
            const point = pcCom.points[index];
            worldPoints.push(uitransform.convertToWorldSpaceAR(point.toVec3()).toVec2())
        }
        return worldPoints;
    }

    private isIntersection(pcCom0: PolygonCollider2D, pcCom1: PolygonCollider2D): boolean {
        const pints0 = this.polygonColliderToWorldPoints(pcCom0)
        const pints1 = this.polygonColliderToWorldPoints(pcCom1)
        return Intersection2D.polygonPolygon(pints0, pints1)
    }

    update(deltaTime: number) {
        if(this.isIntersection(this.polygonCollider1, this.polygonCollider2)) {
            // console.log("yes")
            this.label.string = "是否碰撞:" + "yes"
        } else {
            // console.log("no")
            this.label.string = "是否碰撞:" + "no"
        }
    }

    /**
     * 将节点size转换为4个点,世界坐标系下
     * @param uiTranshform 
     * @returns 世界坐标下Points
     */
    private uiTransformSizeToWorldPoints(uiTranshform: UITransform): Vec2[] {
        const nodeSize = uiTranshform.contentSize
        const worldPoints = []
        const widthHalf = nodeSize.width / 2
        const witchHeight = nodeSize.height / 2
        // 左上
        worldPoints[0] = v2(
            uiTranshform.node.position.x + widthHalf * -1,
            uiTranshform.node.position.y + witchHeight
        ) 
        // 右上
        worldPoints[1] = v2(
            uiTranshform.node.position.x + widthHalf,
            uiTranshform.node.position.y + witchHeight,
        ) 
        // 右下
        worldPoints[2] = v2(
            uiTranshform.node.position.x + widthHalf,
            uiTranshform.node.position.y + witchHeight * -1
        ) 
        //左下
        worldPoints[3] = v2(
            uiTranshform.node.position.x + widthHalf * -1,
            uiTranshform.node.position.y + witchHeight * -1
        ) 
        return worldPoints
    }
}